import styles from './index.module.scss'
import { NavBar, Form, Input, List, Button, Toast } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router'
import { LoginForm } from '@/types/data'
import { useDispatch } from 'react-redux'
import { login, getCode } from '@/store/actions/login'
import { useEffect, useRef, useState } from 'react'
import { FormInstance } from 'antd-mobile/es/components/form'
import { InputRef } from 'antd-mobile/es/components/input'

export default function Login() {
  const history = useHistory()
  const dispatch = useDispatch();
  const formRef = useRef<FormInstance>(null);
  const mobileRef = useRef<InputRef>(null);
  const [timeLeft, setTimeLeft] = useState(0);
  // timerRef 用于储存定时器ID
  const timerRef = useRef(-1);
  const location = useLocation<{from: string}>();

  const onFinish = async (values: LoginForm) => {
    await dispatch(login(values));
    Toast.show({
      content: '登录成功',
      icon: 'success',
      duration: 1000,
      afterClose: () => {
        let pathName = location.state ? location.state.from : '/home'
        history.replace(pathName);
      }
    });
  }

  const onGetCode = () => {
    const value = formRef.current?.getFieldValue('mobile');
    const error = formRef.current?.getFieldError('mobile');
    if (!value || error!.length > 0) {
      mobileRef.current?.focus();
      return
    }
    dispatch(getCode(value));
    setTimeLeft(60);
    timerRef.current = window.setInterval(() => {
      // 需要使用回调函数形式的 setTimeLeft
      setTimeLeft((state) => state - 1);
    }, 1000);
  }

  //倒计时为0时，清理定时器
  useEffect(() => {
    if (timeLeft === 0) {
      clearInterval(timerRef.current);
    }
  }, [timeLeft]);

  //组件销毁时，清理定时器
  useEffect(() => {
    return () => {
      clearInterval(timerRef.current)
    }
  }, [])

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}></NavBar>

      {/* 表单 */}
      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form ref={formRef} onFinish={onFinish}>
          <Form.Item
            name='mobile'
            className="login-item"
            validateTrigger={['onChange', 'onBlur']}
            rules={[
              {
                required: true,
                message: '手机号不能为空',
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误',
              }
            ]}
          >
            <Input ref={mobileRef} placeholder="请输入手机号"></Input>
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={
              <span
                className="code-extra"
                onClick={onGetCode}
              >
                {/* 判断是否开启定时器，没开启展示 发送验证码，开启后展示倒计时 */}
                {timeLeft === 0 ? '发送验证码' : `${timeLeft}s后重新获取`}
              </span>}
          >
            <Form.Item
              className="login-item"
              name='code'
              validateTrigger={['onChange', 'onBlur']}
              rules={[
                {
                  required: true,
                  message: '验证码不能为空',
                },
                {
                  pattern: /^\d{6}$/,
                  message: '验证码格式错误',
                },
              ]}
            >
              <Input placeholder="请输入验证码"></Input>
            </Form.Item>
          </List.Item>
          <Form.Item>
            <Button type='submit' color="primary" block className="login-submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}